const url = 'https://api.weixin.qq.com/cgi-bin/token'
const appid = 'wx2771a675c9895f3d'
const secret = '3af3cfba61e1e8c4c4330e946304e0a0'

module.exports = getAccessToken = async ()=>{
    const fs = require('fs')
    let tokenStr = ''
    const axios = require('axios')
    const uri = `${url}?grant_type=client_credential&appid=${appid}&secret=${secret}`
    try {
        tokenStr = fs.readFileSync('./token.txt')
        const token = JSON.parse(tokenStr)
        if(!token && Date.now() < token.exp) {
            const {data} = await axios.get(uri)
            // 设置token过期时间
            data.exp = data.expires_in*1000 + Date.now() - 60*10*1000
    
            return data
        } else {
            return token
        }
    } catch (error) {
        const {data} = await axios.get(uri)
        // 设置token过期时间
        data.exp = data.expires_in*1000 + Date.now() - 60*10*1000
        fs.writeFileSync('./token.txt', JSON.stringify(data))
        return data
    }



}
